package com.deercrowing.takeaway.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.common.util.SerialIDGenerator;
import com.deercrowing.takeaway.context.BaseContext;
import com.deercrowing.takeaway.dao.AddressMapper;
import com.deercrowing.takeaway.entity.AddressEntity;
import com.deercrowing.takeaway.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 地址表(Address)表服务实现类
 *
 * @author guoyongxiang
 * @since 2024-07-19 09:41:26
 */
@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressEntity> implements AddressService {

    @Autowired
    AddressMapper addressMapper;

    @Override
    public List<AddressEntity> searchByUserId(Long id) {
        List<AddressEntity> addressEntityList = addressMapper.selectListByUserId(id);

        if (addressEntityList.size() < 0 || addressEntityList == null){
            throw new NullPointerException();
        }

        return addressEntityList;
    }

    @Override
    public void saveInfo(AddressEntity addressEntity) {
        SerialIDGenerator serialIDGenerator = new SerialIDGenerator();
        Integer total = addressMapper.countUserId(BaseContext.getCurrentId()) == null ? 0 : addressMapper.countUserId(BaseContext.getCurrentId());
        // 每个用户只可以保存36个地址
        if (total >= 36){
            throw new BusinessException("已超过最大地址保存数目");
        }

        addressEntity.setId(Long.parseLong(serialIDGenerator.generateID()))
                     .setUsersId(BaseContext.getCurrentId())
                     .insert();
    }

    @Override
    public void setDefaultAddress(AddressEntity addressEntity) {
        addressEntity.setIsDefault(1)
                     .updateById();
    }

    @Override
    public AddressEntity searchDefaultAddressByUserId(Long id) {
        AddressEntity addressEntity = addressMapper.selectDefaultAddressByUserId(id);

        if (ObjectUtils.isEmpty(addressEntity)){
            throw new NullPointerException();
        }

        return addressEntity;
    }
}

